package cn.dxh.stagefinal.service.impl;

import cn.dxh.stagefinal.bean.Employee;
import cn.dxh.stagefinal.dao.LoginDao;
import cn.dxh.stagefinal.service.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 2019/12/11 19:12
 *
 * @author Wenhao Lee
 * 心向远方，不负厚望。
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private LoginDao loginDao;

    @Transactional
    @Override
    public Employee login(String loginName, String password) {
        UsernamePasswordToken token = new UsernamePasswordToken(loginName, password);
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        if (subject.isAuthenticated()) {
            Employee employee = (Employee) subject.getPrincipal();
            Integer loginCount = employee.getLoginCount();
            Map<String, Object> map = new HashMap<>();
            map.put("id", employee.geteId());
            map.put("eEndTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            map.put("loginCount", ++loginCount);
            loginDao.updateLoginCount(map);
            return (Employee) subject.getPrincipal();
        } else {
            return null;
        }
    }
}
